<template>
  <div style="border: black 0px solid;background-color: #f6f6f6">

    <div style="margin-top: 20px;margin-bottom: 20px;" class="AwsCenter">

      <!--   左边   -->
      <div style="border: 0px black solid;width: 700px;height: 830px;display: flex;flex-direction: column">

      <!--   日期啥的   -->
        <div style="border: 0px solid black;padding: 10px;display: flex;flex-direction: column;height: 100px">
          <div style="margin-left: auto;display: flex;flex-direction: row;height: 70px">
            <div style="margin-left: 5px">{{format(new Date(), 'yyyy年MM月dd日', { locale: zh })}}</div>
            <div style="margin-left: 20px">{{currentTime}}</div>
            <div style="margin-left: 20px">{{currentDayOfWeek}}</div>
            <div style="margin-left: 10px">{{ weather.description }}</div>
            <!-- 显示天气图标 -->
            <img style="width: 25px;height: 25px" :src="weather.iconUrl" :alt="weather.description" />
            <div style="margin-left: 10px">{{ weather.temperature }}°C</div>
          </div>

          <div style="margin-left: auto;display: flex;flex-direction: row;margin-top: 10px">
            <text>陪伴、倾听、治愈，每一步都算数。</text>
          </div>

        </div>


        <div style="display: flex;flex-direction: row">

          <div style="width: 40%; height: 300px; border: 0px black solid;
            border-radius: 20px; background-color: #8adba0;
            margin-top: 20px; margin-right: 10px; padding: 20px;
            display: flex; flex-direction: column; color: white;">

            <!-- 标题居中 -->
            <text style="align-self: center; font-size: 1.2rem; font-weight: bold;">
              {{homepageForm.sectionName}}
            </text>

            <!-- 正文首行缩进两字符 -->
            <text style="text-indent: 2em; margin-top: 10px; font-size: 0.9rem;">
              {{homepageForm.textContent}}
            </text>
          </div>


          <!--   轮播图   -->
          <div style="width: 60%;border: black 0px solid;margin-top: 20px">
            <el-carousel interval="4000" indicator-position="outside" style="border-radius: 20px">
              <el-carousel-item v-for="(item, index) in images"  :key="index" style="border-radius: 20px">
                <img :src="item.src" :alt="'Image ' + (index + 1)" style="width: 100%; height: auto; border-radius: 20px;" />
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>




        <!-- 办事流程-->
        <div style="width: 100%; height: 270px; border: 0px black solid; border-radius: 20px;
            background-color: white; display: flex; justify-content: center; align-items: center;
            overflow: hidden; position: relative;">

          <!-- 办事流程文本 -->
          <div style="position: absolute; top: 10px; left: 50%; transform: translateX(-50%);
              font-size: 18px; font-weight: bold; color: black; z-index: 10;">
            办事流程
          </div>

          <!-- 不同用户显示不同的图片 -->
          <img v-if="user.usertype === 'client'" src="@/assets/lc/lc1.png"
               style="width: 100%; height: 100%; object-fit: cover;">
          <img v-if="user.usertype === 'counselor'" src="@/assets/lc/lc2.png"
               style="width: 100%; height: 100%; object-fit: cover;">
        </div>




      </div>

    <!--  公告    -->

      <div style="border: black 0px solid;width: 350px;height: 720px;margin-left:20px;background-color: white;border-radius: 20px" >
        <div style="margin-top: 20px" class="AwsCenter">
          <text style="font-size: 23px;font-weight: bold;">公 告 信 息</text>
        </div>

<!--        <div>展示</div>-->
        <div style="border: #A9A9A9 1px solid;margin:10px 20px 10px 20px"></div>

        <div v-for="(item,index) in announceList" :key="item.id"
             :style="{
                width: '90%',
                display: 'flex',
                flexDirection: 'column',
                margin: '20px',
                padding: '10px',
                borderRadius: '20px',
                // 动态设置背景颜色
                backgroundColor: index === 0 ? '#e6a083' : '#f1f2f0'
              }"
        >
          <!-- 公告标题文字-->
          <text :style="{fontWeight: 'bold', fontFamily: 'LiSong Pro Light', color: index === 0 ? 'white' : 'black'}">· 【{{item.title}}】</text>
          <!--公告内容正文-->
          <text :style="{fontFamily: 'LiSong Pro Light', marginTop: '5px', color: index === 0 ? 'white' : 'black'}">{{item.announcementcontent}}</text>
          <!--作者 + 发布时间-->
          <div style="display: flex;flex-direction: row;marginTop: 5px;">
            <text :style="{fontFamily: 'NSimSun', fontWeight: 'bold', fontSize: '14px', color: index === 0 ? 'white' : 'black'}">发布人：{{item.authorname}}</text>
            <text :style="{fontFamily: 'NSimSun', fontWeight: 'bold', fontSize: '14px', marginLeft: '30px', color: index === 0 ? 'white' : 'black'}">{{convertUtcToLocal(item.createdat)}}</text>
          </div>


        </div>

      </div>


    </div>

<!--    <div style="border: 1px black solid;width: 100%;height: 60px;background-color: black;align-items: center" class="AwsCenter">
        <text style="color: white;font-size: x-small">如遇问题请联系？123456789</text>
    </div>-->



  </div>
</template>

<script setup lang="ts">
import {getAnnouncementsService,getTextService,getAnnouncementsServiceTest} from '@/api/announce.js'//引入公告 API、首页介绍 API；
import {onMounted, ref} from "vue";//使用 Vue 的组合式 API；
import {useUserStore} from "@/stores/user/user.js";
import {format} from 'date-fns/format';//用于格式化时间
import zh from 'date-fns/locale/zh-CN';
const userStore=useUserStore()//调用用户状态模块；
const userInfo=userStore.getUser()
import axios from 'axios';
import {getUserService} from "@/api/user.js";

// 替换为你的API密钥和你选择的API URL
const apiKey = '6d1c72ba97c694c35db2358763ef9d6e';//OpenWeatherMap 的 API 密钥
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=31.299379&lon=120.619585&units=metric&lang=zh_cn&appid=${apiKey}`;

const loading = ref(true);//响应式对象，正在加载中
const error = ref<string | null>(null);
const weather = ref({//存储天气信息
  city: '',
  temperature: 0,
  description: '',
  iconUrl: ''
});

// 定义轮播图片数组，包含图片路径
const images = ref([
  { src: new URL('@/assets/mainImg/1.jpg', import.meta.url).href }, // 根据实际情况调整路径
  { src: new URL('@/assets/mainImg/2.jpg', import.meta.url).href },
  { src: new URL('@/assets/mainImg/3.jpg', import.meta.url).href },
  { src: new URL('@/assets/mainImg/4.jpg', import.meta.url).href }
]);

//获取天气数据的函数
const fetchWeatherData = async () => {
  try {
    const response = await axios.get(apiUrl);//向天气服务发请求
    const data = response.data;
    weather.value.city = data.name;
    weather.value.temperature = data.main.temp;
    weather.value.description = data.weather[0].description;

    // 使用OpenWeatherMap提供的图标URL
    weather.value.iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;

    loading.value = false;//数据加载结束
  } catch (err) {
    console.error('获取天气数据失败:', err);
    error.value = '无法获取天气信息，请稍后再试。';
    loading.value = false;
  }
};

// 定义一个响应式的 currentDayOfWeek 变量
const currentDayOfWeek = ref<string>('');

// 获取今天的星期并转换为中文
const getDayOfWeek = (): string => {
  const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const today = new Date();
  return daysOfWeek[today.getDay()];
};

// 定义一个响应式的 currentTime 变量
const currentTime = ref<string>('');

// 更新时间的函数
const updateTime = () => {
  // 使用 JavaScript 的原生方法格式化时间，去掉秒
  currentTime.value = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
};

// 组件挂载时立即更新一次时间，并设置定时器每分钟更新一次

const user=ref('')

const announceList=ref([])

//公告时间格式化
function convertUtcToLocal(utcDateStr: string): string {
  const date = new Date(utcDateStr);
  // 使用 'zh-CN' 区域和 'long' 格式来确保小时为24小时制
  return date.toLocaleString('zh-CN', { hour12: false });
}
onMounted(async ()=>{
  //console.log(userInfo)

  //获取首页介绍内容
  const userRes=await getUserService()
  if (userRes.code===200){
    user.value=userRes.data
  }

  //获取首页信息数据
  await getText()



  //获取公告列表
  const res=await getAnnouncementsService()//异步请求，等待接口响应
  if (res.code===200){
    console.log(res)
    announceList.value=res.data//数据赋值到响应式变量 announceList
    console.log(announceList.value)
  }
  //获取天气信息
  await fetchWeatherData();

  currentDayOfWeek.value = getDayOfWeek();//调用函数 getDayOfWeek() 返回星期几
  updateTime();
  //
  setInterval(updateTime, 1000); // 每隔一分钟调用一次自己

})
// 格式化日期函数
const formatDate=((datetime)=>{
  const str=datetime.toString().split(".")[0]
  return str.replace('T', ' ')
})

//获取首页介绍文字
const getText=(async ()=>{
  const res=await getTextService()
  if (res!=undefined&&res.code===200){
    //console.log(res)
    homepageForm.value={...res.data[0]}
  }
})
//初始化 homepageForm 对象
const homepageForm=ref({
  id:'',
  sectionName:'',
  textContent:'',
  modifiedBy:''
})

</script>

<style scoped>

.el-carousel__item h3 {
  display: flex;
  color: #475669;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.AwsCenter{
  display: flex;
  justify-content: center;
  //align-items: center;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
}
</style>